package com.hsfw.pmauthzuul.filter;

import com.hsfw.dbmodule.entity.UserDetail;
import com.hsfw.dbmodule.utils.JWTUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by RAZR on 15:43 2019/3/22.
 */
@Component
public class AuthFilter  extends OncePerRequestFilter {
    @Value("${JWT.header}")
    private String authHeader;
    @Value("${JWT.tokenHead}")
    private String tokenHead;

    @Autowired
    private JWTUtil jwtUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String authToken = request.getHeader(authHeader);
        if (StringUtils.isNotEmpty(authToken) && authToken.startsWith(tokenHead)) {
            authToken = authToken.substring(tokenHead.length());
        } else {
            // 不按规范,不允许通过验证
            authToken = null;
        }
        String account = jwtUtil.getUserAccountFromToken(authToken);
        if (jwtUtil.containToken(account, authToken) && account != null &&
                SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetail userDetail = jwtUtil.getUserFromToken(authToken);
            if (jwtUtil.validateToken(authToken, userDetail)) {
                UsernamePasswordAuthenticationToken authentication =
                        new UsernamePasswordAuthenticationToken(userDetail, null, userDetail.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        chain.doFilter(request, response);
    }
}
